# -*- coding: UTF-8 -*-
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

from win_mac import Mac

class CustomHandler(BaseHTTPRequestHandler):
    def _send_cors_headers(self):
        """ Sets headers required for CORS """
        self.send_header('Content-type', 'application/json')
        self.send_header("Access-Control-Allow-Origin", "*")
        # self.send_header("Access-Control-Allow-Methods", "*")
        # self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type")
        self.send_header('Access-Control-Allow-Headers', 'Access-Control-Request-Headers,Content-Type,Access-Control-Request-Method,Connection')

    def do_OPITION(self):
        pass

    def do_GET(self):
        self.send_response_only(200)
        # self.end_headers()
        if self.path == '/mac':
            self.send_response(200)
            self._send_cors_headers()
            self.end_headers()
            mac = Mac.load_mac()
            message = ''
            code = 404
            if mac is not None and len(mac)>2:
                message = 'success'
                code = 200
            else:
                message = 'fail' 
            bean = {"message":message,"code":code,"data":mac}
            json_string = json.dumps(bean)
            # json_string = json.dump(bean,)
            # print(json_string)
            self.wfile.write(json_string.encode('utf-8'))
        else:
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'Not Found')
    
class MyService:
    
    @staticmethod
    def run():
        server_address = ("", 8249)
        httpd = HTTPServer(server_address, CustomHandler)
        print("服务器地址：http://localhost:8249/mac")
        httpd.serve_forever()

if __name__ == '__main__':
    MyService.run()